#include <stdio.h>
#include "string.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_err.h"
#include "driver/gpio.h"
#include "esp_private/esp_clk.h"
#include "wifi_apstation.h"
#include "TimerConfig.h"
#include "freertos/semphr.h"
#include "esp_flash.h"

#include "esp_pm.h"
#include "esp_sleep.h"
#include "driver/rtc_io.h"

#include "WiFiIno_flash.h"
#include "WebServer.h"
#include "Datapara.h"
#include "HC_SR04.h"



#include "esp_event.h"
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "esp_http_client.h"
#include "esp_https_ota.h"
#include "protocol_examples_common.h"

static const char* TAG = "MAIN";

EventGroupHandle_t  data_analy_event_group;


#define BOOT_GPIO  GPIO_NUM_9  //boot pin

// #define GPIO11_LED GPIO_NUM_11   //LED pin

SemaphoreHandle_t file_mutex;

int8_t WiFiInoCfgStatus = 1;  
int8_t OTA_FINISH_OR_FAIL = 0;




static void wifi_power_save(void)
{
    esp_wifi_set_ps(WIFI_PS_MAX_MODEM);    //设置电源管理
}


static void example_deep_sleep_register_rtc_timer_wakeup(void)
{
    const int wakeup_time_sec = 1800;   //30min唤醒一次
    printf("Enabling timer wakeup, %ds\n", wakeup_time_sec);
    ESP_ERROR_CHECK(esp_sleep_enable_timer_wakeup(wakeup_time_sec * 1000000));
}



void app_main(void)
{
 
   example_deep_sleep_register_rtc_timer_wakeup(); //深度睡眠唤醒时间设置


    //初始化NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        //NVS出现错误，执行擦除
        ESP_ERROR_CHECK(nvs_flash_erase());
        //重新尝试初始化
        ESP_ERROR_CHECK(nvs_flash_init());
    }

    //创建一个函数解析（json数据）相关的事件组
    data_analy_event_group = xEventGroupCreate();

    file_mutex = xSemaphoreCreateMutex();

    TimerConfigInit();

    gpio_set_direction(BOOT_GPIO, GPIO_MODE_INPUT);



    GetWiFiInoFromNvs();

    GPIO_HC_SR04_Start_Init();

    web_server_init();  /*放在wifi初始化前面，保证先完成队列的创建*/
    
    wifi_apsta_init();

    while(1)
    {
        vTaskDelay(pdMS_TO_TICKS(1000));
    } 
}
